package db_manager

import (
	"html/template"
	"net/http"

	"github.com/gorilla/mux"
)

// 添加静态文件和前端界面
func (s *HTTPServer) addStaticRoutes(router *mux.Router) {
	// 提供静态文件
	router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./web/static"))))

	// 管理页面
	router.HandleFunc("/", s.handleDashboard).Methods("GET")
	router.HandleFunc("/devices", s.handleDevicesPage).Methods("GET")
}

// handleDashboard 处理主页请求
func (s *HTTPServer) handleDashboard(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// 获取设备数量
	count, err := s.manager.CountDevices(ctx)
	if err != nil {
		http.Error(w, "获取设备数量失败", http.StatusInternalServerError)
		return
	}

	data := map[string]interface{}{
		"Title":       "设备管理仪表盘",
		"DeviceCount": count,
	}

	// 渲染模板
	tmpl := template.Must(template.New("dashboard").Parse(dashboardHTML))
	tmpl.Execute(w, data)
}

// handleDevicesPage 处理设备列表页面请求
func (s *HTTPServer) handleDevicesPage(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// 获取设备列表
	devices, err := s.manager.ListDevices(ctx)
	if err != nil {
		http.Error(w, "获取设备列表失败", http.StatusInternalServerError)
		return
	}

	data := map[string]interface{}{
		"Title":   "设备列表",
		"Devices": devices,
	}

	// 渲染模板
	tmpl := template.Must(template.New("devices").Parse(devicesHTML))
	tmpl.Execute(w, data)
}

// 主页HTML模板
const dashboardHTML = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.Title}} - ZKP认证系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        header {
            background: #4CAF50;
            color: white;
            padding: 1rem;
            margin-bottom: 2rem;
        }
        .card {
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .stats {
            display: flex;
            justify-content: space-around;
            flex-wrap: wrap;
        }
        .stat-card {
            background: #f9f9f9;
            border-left: 4px solid #4CAF50;
            padding: 15px;
            flex: 1 1 200px;
            margin: 10px;
            border-radius: 4px;
        }
        .stat-value {
            font-size: 2rem;
            font-weight: bold;
            color: #4CAF50;
        }
        .nav {
            margin-bottom: 20px;
        }
        .nav a {
            text-decoration: none;
            color: #4CAF50;
            margin-right: 15px;
            padding: 5px 10px;
        }
        .nav a:hover {
            background: #f0f0f0;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>ZKP设备认证管理系统</h1>
        </header>
        
        <div class="nav">
            <a href="/">首页</a>
            <a href="/devices">设备管理</a>
        </div>
        
        <div class="card">
            <h2>系统概况</h2>
            <div class="stats">
                <div class="stat-card">
                    <h3>已注册设备</h3>
                    <div class="stat-value">{{.DeviceCount}}</div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <h2>快速导航</h2>
            <ul>
                <li><a href="/devices">查看所有设备</a></li>
                <li><a href="/api/devices">设备API (JSON)</a></li>
            </ul>
        </div>
    </div>
</body>
</html>`

// 设备列表HTML模板
const devicesHTML = `<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.Title}} - ZKP认证系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 20px;
            color: #333;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        header {
            background: #4CAF50;
            color: white;
            padding: 1rem;
            margin-bottom: 2rem;
        }
        .card {
            background: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .nav {
            margin-bottom: 20px;
        }
        .nav a {
            text-decoration: none;
            color: #4CAF50;
            margin-right: 15px;
            padding: 5px 10px;
        }
        .nav a:hover {
            background: #f0f0f0;
            border-radius: 4px;
        }
        .key-data {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .button {
            display: inline-block;
            padding: 8px 16px;
            border: none;
            background: #4CAF50;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .button.delete {
            background: #f44336;
        }
        .button:hover {
            opacity: 0.9;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>ZKP设备认证管理系统</h1>
        </header>
        
        <div class="nav">
            <a href="/">首页</a>
            <a href="/devices">设备管理</a>
        </div>
        
        <div class="card">
            <h2>设备列表</h2>
            {{if .Devices}}
                <table>
                    <thead>
                        <tr>
                            <th>设备ID</th>
                            <th>公钥 Y1</th>
                            <th>公钥 Y2</th>
                            <th>会话ID</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {{range .Devices}}
                        <tr>
                            <td>{{.DeviceID}}</td>
                            <td class="key-data" title="{{.Y1}}">{{.Y1}}</td>
                            <td class="key-data" title="{{.Y2}}">{{.Y2}}</td>
                            <td>{{if .SessionID}}{{.SessionID}}{{else}}<span style="color:gray">未设置</span>{{end}}</td>
                            <td>
                                <button class="button delete" onclick="deleteDevice('{{.DeviceID}}')">删除</button>
                            </td>
                        </tr>
                        {{end}}
                    </tbody>
                </table>
            {{else}}
                <p>没有已注册的设备</p>
            {{end}}
        </div>
    </div>
    
    <script>
        function deleteDevice(deviceId) {
            if (confirm('确定要删除设备 ' + deviceId + ' 吗？')) {
                fetch('/api/devices/' + deviceId, {
                    method: 'DELETE'
                })
                .then(response => {
                    if (response.ok) {
                        alert('设备已删除');
                        window.location.reload();
                    } else {
                        response.text().then(text => {
                            alert('删除失败: ' + text);
                        });
                    }
                })
                .catch(error => {
                    alert('删除时出错: ' + error);
                });
            }
        }
    </script>
</body>
</html>`
